let app = new Vue({
    el: '#app',
    data: {
        admin: JSON.parse(sessionStorage.getItem("admin")),
        users: []
    },
    created() {

        layui.use(['form'], function () {
            let form = layui.form;

            // 查询所有学生
            $.ajax({
                url: 'http://localhost:8080/user/select',
                type: 'get',
                data: { role: 1 },
                success: function (vo) {
                    if (vo.code == 200) {
                        app.users = vo.data;
                        $.each(vo.data, function (i, u) {
                            $("#receiveUserName").append("<option value='" + u.userName + "'>" + u.userName + "</option>");
                        });
                    }
                    form.render();
                }
            });
        });

    },
    methods: {
        send: function () {
            if ($("#title").val() == '' || $("#content").val() == '' || $("#receiveUserName").val() == '') {
                layer.msg("必填字段不能为空", { offset: 't', icon: 2 });
                return;
            }

            // 获取接收者用户的下标 ，从而获取接收者用户的用户Id和真实姓名
            let index = -1;
            for (let i = 0; i < this.users.length; i++) {
                if (this.users[i].userName == $("#receiveUserName").val()) {
                    index = i;
                }
            }

            let params = {
                title: $("#title").val(),
                content: $("#content").val(),
                sendUserId: this.admin.userId,
                sendUserName: this.admin.userName,
                sendRealName: this.admin.realName,
                receiveUserId: this.users[index].userId,
                receiveUserName: this.users[index].userName,
                receiveRealName: this.users[index].realName
            }

            $.ajax({
                url: 'http://localhost:8080/message/add',
                type: 'post',
                data: params,
                success: function (vo) {
                    if (vo.code == 200) {
                        layer.msg(vo.data, { offset: 't', icon: 1 });
                        // $("#title").val('');
                        // $("#content").val('');
                        // $("#receiveUserName option:first").prop('selected', 'selected');
                        // $("#receiveUserName").selectedIndex=-1;

                        // 延迟1秒执行代码
                        setTimeout(function(){
                            // 重置表单
                            $('#sendForm')[0].reset();
                            layui.form.render();
                        },1000);
                        
                        
                    } else {
                        layer.msg(vo.message, { offset: 't', icon: 2 });
                    }
                }
            });
        }
    }
});